//
//  serverManager.swift
//  MyNews
//
//  Created by DF-Mac on 16/11/30.
//  Copyright © 2016年 DF-Mac. All rights reserved.
//

import UIKit
import Alamofire

// tags to identify a specific server request while receiving respone
let LOGIN_REQUEST_TAG = 1000
let GET_NEWS_INFO_REQUEST_TAG = 1100


// server response handler protocol. have two methods one is for success and another for failure
@objc protocol serverResponseHandler {
    func requestFinished(_ responseData: Data,requestTag:Int)
    
    func requestFailed(_ error:NSError)
    
}
class serverManager: NSObject {
    
    var requestDelegate : serverResponseHandler?
    
    /// (定义闭包)完成回调属性,requestTag用于多个网络请求方法的标识
    var completionCallBack : ((_ requestTag:Int,_ data:Data)->())?
    
    
    
    func makeHttpGetRequest(methodName:String,getBodyData:String,requestTag:Int) {

        let serverAddress = "http://api.tianapi.com/"
        
        var urlString = "\(serverAddress)"+"\(methodName)?"+"\(getBodyData)"
        print("urlString\(urlString)")
        
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!
        
        let url = NSURL(string: urlString as String)
        
        let request = NSURLRequest(url: url as! URL, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 10)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            if response != nil {
                
                let responseStatusCode=(response as! HTTPURLResponse).statusCode
                
                if data?.count == 0 {
                    self.requestDelegate?.requestFailed(NSError(domain: "", code: responseStatusCode, userInfo: [NSLocalizedDescriptionKey:"An error occurred. Try log out and then log in again"]))
                } else if responseStatusCode == 200 {
                    //方法一:delegate
                    self.requestDelegate?.requestFinished(data!, requestTag: requestTag)
                    print("\(data)")
                    
                    //方法二:闭包
                    self.completionCallBack?(requestTag,data!)
                    
                } else{
                    let errorString = HTTPURLResponse.localizedString(forStatusCode: responseStatusCode)
                    self.requestDelegate?.requestFailed(NSError(domain: "", code: responseStatusCode, userInfo: [NSLocalizedDescriptionKey:errorString]))
                }
            }
            else if error != nil {
                self.requestDelegate?.requestFailed(error as! NSError)
            }else{
                self.requestDelegate?.requestFinished(data!, requestTag: requestTag)
            }
        }
        
        task.resume()
        
    }
    
    // update news
    func getNews(newsType: String, num: Int, page: Int)  {
        let authKey = "6bcc592cde9eec424cb2cb17d4c82ced"
//        let num = 10
        let postString = "key=\(authKey)&num=\(num)&page=\(page)"
        makeHttpGetRequest(methodName: newsType, getBodyData: postString, requestTag: GET_NEWS_INFO_REQUEST_TAG)
    }

}
